package cn.bonoon.kernel.config;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;

import cn.bonoon.kernel.util.StringHelper;

public abstract class ConfigParser extends AbstractSingleBeanDefinitionParser {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());

	protected Element element(Element element, String name) {
		return DomUtils.getChildElementByTagName(element, name);
	}

	/**
	 * 读取节点内容
	 * @param element
	 * @param name
	 * @return
	 */
	protected String getText(Element element, String name) {
		Element text = DomUtils.getChildElementByTagName(element, name);
		return null == text ? null : text.getTextContent();
	}

	protected List<Element> elements(Element element, String name) {
		return DomUtils.getChildElementsByTagName(element, name);
	}

	protected List<Element> elements(Element element, String[] names) {
		return DomUtils.getChildElementsByTagName(element, names);
	}

	public boolean getBool(Element element, String name) {
		return getBool(element, name, false);
	}

	public boolean getBool(Element element, String name, boolean defaultValue) {
		String b = element.getAttribute(name);
		if (StringHelper.isEmpty(b))
			return defaultValue;
		return Boolean.parseBoolean(b);
	}

	public int getInt(Element element, String name) {
		return StringHelper.toint(element.getAttribute(name));
	}
	
	public int getOrdinal(Element element){
		return getInt(element, "ordinal");
	}

	public List<String> getList(Element element, String name) {
		return StringHelper.toList(element.getAttribute(name));
	}
	/**
	 * 先读取节点的属性，如果没有该属性的值，再根据名称查找是否有相同名称的节点
	 * @param element
	 * @param name
	 * @return
	 */
	public String getValue(Element element, String name){
		String value = element.getAttribute(name);
		if(StringHelper.isEmpty(value)){
			return getText(element, name);
		}
		return value;
	}

	public String getName(Element element) {
		return getValue(element, NAME_ATTRIBUTE);
	}

	public String getId(Element element) {
		return element.getAttribute(ID_ATTRIBUTE);
	}

	public Class<?> getClass(Element element, String name) {
		String className = element.getAttribute(name);
		if (StringHelper.isNotEmpty(className)) {
			try {
				return Class.forName(className);
			} catch (Throwable t) {
				//找不到class
			}
		}
		return null;
	}

	public Class<?> getClass(Element element) {
		return getClass(element, "class");
	}
}
